package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Config;
import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DefaultHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        // TODO: [学号/姓名]
        // 1. 获取请求路径（可能需要将 / 映射到 index.html）
        // 2. 根据 Config.getWebRoot() 构建完整文件路径
        String requestPath = request.getUrl();
        if (requestPath.equals("/")) {
            requestPath = "/index.html";
        }

        Path filePath = Paths.get(Config.getInstance().getWebRoot(), requestPath.substring(1));

        try {
            if (Files.exists(filePath) && !Files.isDirectory(filePath)) {
                byte[] fileBytes = Files.readAllBytes(filePath);

                // TODO: [学号/姓名] 确定并设置正确的 Content-Type (例如 text/html, image/jpeg 等)
                String contentType = determineContentType(filePath.toString());

                // 写入 200 OK 响应头
                response.write(("HTTP/1.1 200 OK\r\n").getBytes());
                response.write(("Content-Type: " + contentType + "\r\n").getBytes());
                response.write(("Content-Length: " + fileBytes.length + "\r\n").getBytes());
                response.write(("\r\n").getBytes());

                // 写入文件内容
                response.write(fileBytes);
            } else {
                // 文件不存在或路径错误，返回 404
                String content = "<h1>404 Not Found</h1><p>The requested resource " + request.getUrl() + " was not found.</p>";
                response.write(("HTTP/1.1 404 Not Found\r\n").getBytes());
                response.write(("Content-Type: text/html; charset=UTF-8\r\n").getBytes());
                response.write(("Content-Length: " + content.getBytes().length + "\r\n").getBytes());
                response.write(("\r\n").getBytes());
                response.write(content.getBytes());
            }
        } catch (IOException e) {
            // TODO: [222024321072009/郑子寒] 文件读取异常，返回 500 Internal Server Error
            try{
                String errorContent = "<h1>500 Internal Server Error</h1><p>Error reading file: " + e.getMessage() + "</p>";
                response.write(("HTTP/1.1 500 Internal Server Error\r\n").getBytes());
                response.write(("Content-Type: text/html; charset=UTF-8\r\n").getBytes());
                response.write(("Content-Length: " + errorContent.getBytes().length + "\r\n").getBytes());
                response.write(("Connection: close\r\n").getBytes());
                response.write(("\r\n").getBytes());
                response.write(errorContent.getBytes());
            }catch (IOException ioException){ /* ignore */}
        } finally {
            try {
                response.flush();
            } catch (IOException e) { /* ignore */ }
        }
    }
    private String determineContentType(String fileName) {
        if (fileName.endsWith(".html") || fileName.endsWith(".htm")) {
            return "text/html; charset=UTF-8";
        } else if (fileName.endsWith(".css")) {
            return "text/css";
        } else if (fileName.endsWith(".js")) {
            return "application/javascript";
        } else if (fileName.endsWith(".png")) {
            return "image/png";
        } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if (fileName.endsWith(".gif")) {
            return "image/gif";
        } else {
            return "application/octet-stream";
        }
    }
}